﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using System.Runtime.InteropServices;

namespace RAC
{
    public partial class SelectForm : Form
    {
        static private string strBeforePathText = "リネームしたいファイルのあるフォルダを選択するかドラッグして下さい";
        static private string strAfterPathText = "コピーしたいフォルダを選択するかドラッグしてください";
        static private string strBeforeNameText = "リネームしたい名前";
        static private string strAfterNameText = "リネームされた名前";

        static private bool s_bLeftPathFlag = false;
        static private bool s_bRightPathFlag = false;

        static private int s_bCopyAllFlag = 0;
        static private int s_iCopyFileMax = 0, s_iCopyFileCounter = 0;

        static bool[] s_bRenameCheckBox = new bool[(int)RenameString.RenameType.MaxRename];

        private enum ItemType
        {
            ItemFolder,   //フォルダ
            ItemFile,     //ファイル
            ItemBinFile,  //バイナリファイル
            ItemTop,      //トップ
            ItemMax,
        };
#if DEBUG
/*
        int s_iStartTime, s_iEndTime;
            s_iStartTime = Environment.TickCount;
            s_iEndTime = Environment.TickCount;
            Console.WriteLine("1:{0}ミリ秒", s_iEndTime - s_iStartTime);
*/
#endif

        //-------------------------------------------------------------------
        // コンストラクタ
        //-------------------------------------------------------------------
        public SelectForm()
        {
            InitializeComponent();
        }
        //-------------------------------------------------------------------
        // 開始時
        //-------------------------------------------------------------------
        private void SelectForm_Shown(object sender, EventArgs e)
        {
            //iniファイル初期設定
            string strIniFile = Path.ChangeExtension(Application.ExecutablePath, ".ini");
            if (File.Exists(strIniFile))
            {
                using (StreamReader reader = new StreamReader(new FileStream(strIniFile, FileMode.Open, FileAccess.ReadWrite)))
                {
                    NormalCheckBox.Checked = bool.Parse(reader.ReadLine());
                    ToupperCheckBox.Checked = bool.Parse(reader.ReadLine());
                    TolowerCheckBox.Checked = bool.Parse(reader.ReadLine());
                    FirsttoupperCheckBox.Checked = bool.Parse(reader.ReadLine());
                    FirsttolowerCheckBox.Checked = bool.Parse(reader.ReadLine());
                    TotitlecaseCheckBox.Checked = bool.Parse(reader.ReadLine());
                    PreupCheckBox.Checked = bool.Parse(reader.ReadLine());

                    BeforePathTextBox.Text = reader.ReadLine();
                    AfterPathTextBox.Text = reader.ReadLine();
                    BeforeNameTextBox.Text = reader.ReadLine();
                    AfterNameTextBox.Text = reader.ReadLine();

                    int x = int.Parse(reader.ReadLine());
                    int y = int.Parse(reader.ReadLine());
                    int width = int.Parse(reader.ReadLine());
                    int height = int.Parse(reader.ReadLine());
                    Location = new Point(x, y);
                    Size = new Size(width, height);
                }
            }
            else
            {
                BeforePathTextBox.Text = strBeforePathText;
                AfterPathTextBox.Text = strAfterPathText;
                BeforeNameTextBox.Text = strBeforeNameText;
                AfterNameTextBox.Text = strAfterNameText;
            }
            FileNameToolStripStatusLabel.Text = "";
            //フラグ設定を先に
            BTextBox_TextChanged(sender, e);
            RenameCheckBox_CheckedChanged(sender, e);
            //それからテキスト系を
            PathTextListViewAdd(s_bLeftPathFlag, s_bRightPathFlag);
            NameTextBox_TextChanged(sender, e);
        }
        //-------------------------------------------------------------------
        // 終了時
        //-------------------------------------------------------------------
        private void SelectForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            string strIniFile = Path.ChangeExtension(Application.ExecutablePath, ".ini");
            using (StreamWriter writer = new StreamWriter(new FileStream(strIniFile, FileMode.Create)))
            {
                writer.WriteLine(NormalCheckBox.Checked);
                writer.WriteLine(ToupperCheckBox.Checked);
                writer.WriteLine(TolowerCheckBox.Checked);
                writer.WriteLine(FirsttoupperCheckBox.Checked);
                writer.WriteLine(FirsttolowerCheckBox.Checked);
                writer.WriteLine(TotitlecaseCheckBox.Checked);
                writer.WriteLine(PreupCheckBox.Checked);
                //ネームプレート
                writer.WriteLine(BeforePathTextBox.Text);
                writer.WriteLine(AfterPathTextBox.Text);
                writer.WriteLine(BeforeNameTextBox.Text);
                writer.WriteLine(AfterNameTextBox.Text);
                //フォーム位置
                writer.WriteLine(Location.X);
                writer.WriteLine(Location.Y);
                writer.WriteLine(Size.Width);
                writer.WriteLine(Size.Height);
            }
        }
        //--------------------------------------------------------------------------
        // パスの項目を追加
        //--------------------------------------------------------------------------
        private void PathItemAdd(ListView lv1, string strPath)
        {
            lv1.Items.Clear();
            //トップフォルダを追加、 「C:\」（階層がトップ）の時は追加しない
            if (AllFileRadioButton.Checked == true && strPath[strPath.Length - 2] != ':')
            {
                ListViewItem toplvi = lv1.Items.Add("上のディレクトリへ");
                toplvi.ImageIndex = (int)ItemType.ItemTop;
            }
            //フォルダを追加
            string[] strDirectories = Directory.GetDirectories(strPath);
            foreach (string strDirectory in strDirectories)
            {
                string strDirName = Path.GetFileName(strDirectory);
                string strChangeName = RenameString.SetRename(s_bRenameCheckBox, strDirName, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                //リネーム対象 か　全ファイル追加
                if (strChangeName != strDirName || AllFileRadioButton.Checked == true)
                {
                    ListViewItem lvi = lv1.Items.Add(strDirName);
                    lvi.ImageIndex = (int)ItemType.ItemFolder;
                }
            }
            //ファイルを追加
            string[] strFiles = Directory.GetFiles(strPath);
            foreach (string strFile in strFiles)
            {
                string strFileName = Path.GetFileName(strFile);
                string strChangeName = RenameString.SetRename(s_bRenameCheckBox, strFileName, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                //リネーム対象
                if (strChangeName != strFileName || AllFileRadioButton.Checked == true)
                {
                    FileInfo fi = new FileInfo(strFile);
                    ListViewItem lvi = lv1.Items.Add(strFileName);
                    long size = (fi.Length / 1024 >= 1) ? fi.Length / 1024 : 1;
                    lvi.SubItems.Add("");
                    lvi.SubItems.Add(size.ToString() + " KB");
                    lvi.SubItems.Add(File.GetLastWriteTime(strFile).ToString());
                    //ファイル情報を全て保存
                    string strRead;
                    using (StreamReader reader = new StreamReader(new FileStream(strFile, FileMode.Open, FileAccess.ReadWrite), RenameString.GetEncoding(strFile)))
                    {
                        strRead = reader.ReadToEnd();
                        //バイナリファイルチェック(\0がなければバイナリ)
                        if (strRead.IndexOf('\0') != -1)
                        {
                            lvi.ImageIndex = (int)ItemType.ItemBinFile;
                        }
                        else
                        {
                            lvi.ImageIndex = (int)ItemType.ItemFile;
                            lvi.Tag = strRead;
                        }
                    }
                }
            }
            lv1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
        //--------------------------------------------------------------------------
        // パスの項目を追加
        //--------------------------------------------------------------------------
//        private void PathItemUpdate(ListView lv1, string strPath)
        private void PathItemUpdate()
        {
            for(int i = 0; i < FolderLeftListView.Items.Count; i++)
            {
                ListViewItem item = FolderLeftListView.Items[i];
                string strDirName = item.Text;
                string strChangeName = RenameString.SetRename(s_bRenameCheckBox, strDirName, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);

                if (FolderRightListView.Items.Count != 0)
                {
                    ListViewItem rItem = FolderRightListView.Items[i];
                    rItem.Text = strChangeName;
                }
                if (item.ImageIndex == (int)ItemType.ItemFile || item.ImageIndex == (int)ItemType.ItemFolder)
                {
                    if (strChangeName != strDirName)
                    {
                        item.ForeColor = Color.Green;
                    }
                    else
                    {
                        item.ForeColor = Color.Black;
                    }
                }
                if (item.ImageIndex == (int)ItemType.ItemFile)
                {
                    if (item.Tag != null)
                    {
                        string strReadChange = RenameString.SetRename(s_bRenameCheckBox, (string)item.Tag, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                        if (strReadChange == (string)item.Tag)
                        {
                            item.SubItems[1].Text = "";
                        }
                        else
                        {
                            item.SubItems[1].Text = "*";
                        }
                    }
                }
            }
        }
        //-------------------------------------------------------------------
        // リストビューに追加
        //-------------------------------------------------------------------
        private void PathTextListViewAdd(bool bLeftFlag, bool bRightFlag)
        {
            //高速化
            FolderLeftListView.BeginUpdate();
            FolderRightListView.BeginUpdate();
            //パス設定
            if (bLeftFlag)
            {
                s_iCopyFileCounter = 0;
                PathItemAdd(FolderLeftListView, BeforePathTextBox.Text);
//                PathItemUpdate(FolderLeftListView, BeforePathTextBox.Text);

                CountCopyPath(BeforePathTextBox.Text);
                s_iCopyFileMax = s_iCopyFileCounter;
                FileCountToolStripStatusLabel.Text = "「全てをコピー」対象ファイル数:" + s_iCopyFileMax.ToString() + "個";
                statusStrip1.Update();
            }
            if (bRightFlag)
            {
                PathItemAdd(FolderRightListView, AfterPathTextBox.Text);
            }
            //右リストビューにリネーム結果を挿入する
            if (bLeftFlag && bRightFlag)
            {
                for (int i = 0; i < FolderLeftListView.Items.Count; i++)
                {
                    ListViewItem item = FolderLeftListView.Items[i];
                    if (item.ImageIndex == (int)ItemType.ItemTop) continue;
                    string strChangeName = RenameString.SetRename(s_bRenameCheckBox, item.Text, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                    if (strChangeName != "")
                    {
                        ListViewItem newItem = FolderRightListView.Items.Insert(i, strChangeName);
                        newItem.ImageIndex = item.ImageIndex;
                        newItem.ForeColor = RenameColorPanel.BackColor;
                    }
                }
            }
            FolderRightListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            //高速化
            FolderRightListView.EndUpdate();
            FolderLeftListView.EndUpdate();
        }
        //-------------------------------------------------------------------
        // コンボボックス追加
        //-------------------------------------------------------------------
        private void ComboUpdate()
        {
            //高速化
            SourceLeftComboBox.BeginUpdate();
            SourceRightComboBox.BeginUpdate();
            SourceLeftComboBox.Items.Clear();
            SourceRightComboBox.Items.Clear();
            //コンボボックス追加
            for (int i = 0; i < FolderLeftListView.Items.Count; i++)
            {
                ListViewItem item = FolderLeftListView.Items[i];
                if (item.ImageIndex == (int)ItemType.ItemTop) continue;
                if (item.ImageIndex == (int)ItemType.ItemFolder) continue;
                if (item.ImageIndex == (int)ItemType.ItemBinFile) continue;
                //色変更
                string strChangeName = RenameString.SetRename(s_bRenameCheckBox, item.Text, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                SourceLeftComboBox.Items.Add(item.Text);
                SourceRightComboBox.Items.Add(strChangeName);
            }
            //強制的に最初を選択にする
            if (SourceLeftComboBox.Items.Count != 0)
            {
                SourceLeftComboBox.SelectedItem = SourceLeftComboBox.Items[0];
                SourceRightComboBox.SelectedItem = SourceRightComboBox.Items[0];
            }
            //高速化
            SourceRightComboBox.EndUpdate();
            SourceLeftComboBox.EndUpdate();
        }
        //--------------------------------------------------------------------------
        // 選択ソース追加
        //--------------------------------------------------------------------------
        private void SelectSourceAdd()
        {
            SourceLeftRichTextBox.Visible = false;
            SourceRightRichTextBox.Visible = false;
            foreach (ListViewItem item in FolderLeftListView.Items)
            {
                if (item.Text == SourceLeftComboBox.Text)
                {
                    item.Selected = true;
                }
                else
                {
                    item.Selected = false;
                }
            }
            foreach (ListViewItem item in FolderLeftListView.SelectedItems)
            {
                string line = (string)item.Tag;
                string strChangeName = RenameString.SetRename(s_bRenameCheckBox, line, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                SourceLeftRichTextBox.Text = line;
                SourceRightRichTextBox.Text = strChangeName;
                RenameLeftRichTextBox.Text = line;
                RenameRightRichTextBox.Text = strChangeName;
                //重い！！！！
                RenameString.RichTextBoxChangeColor(s_bRenameCheckBox, SourceLeftRichTextBox, BeforeNameTextBox.Text);
                RenameString.RichTextBoxChangeColor(s_bRenameCheckBox, SourceRightRichTextBox, AfterNameTextBox.Text);
            }
            SourceLeftRichTextBox.Visible = true;
            SourceRightRichTextBox.Visible = true;
        }
        //-------------------------------------------------------------------
        // コピーファイル
        //-------------------------------------------------------------------
        private void CopyFile(string strFile)
        {
            s_iCopyFileCounter++;
            string strCount = s_iCopyFileCounter.ToString() + "/" + s_iCopyFileMax.ToString() + "個:";
            FileNameToolStripStatusLabel.Text = strCount + Path.GetFileName(strFile) + "をコピー中";
            CopyFileToolStripProgressBar.Value = s_iCopyFileCounter;
            Cursor.Current = Cursors.WaitCursor;
            statusStrip1.Update();
            //リネーム後のファイル名
            string strChangeName = RenameString.SetRename(s_bRenameCheckBox, Path.GetFileName(strFile), BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
            string strChangePath = Path.GetDirectoryName(strFile).Replace(BeforePathTextBox.Text, AfterPathTextBox.Text);
            strChangeName = strChangePath + "\\" + strChangeName;
            //リネーム前のファイルアクセス
            string strbString, straString;
            using (StreamReader reader = new StreamReader(new FileStream(strFile, FileMode.Open, FileAccess.ReadWrite), RenameString.GetEncoding(strFile)))
            {
                strbString = reader.ReadToEnd();
            }
            //リネーム後の文字列
            straString = RenameString.SetRename(s_bRenameCheckBox, strbString, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
            //ファイルはコピーしない
            if (FileCheckBox.Checked == false)
            {
                strChangeName = strFile;
            }
            //リネーム後のパスが無ければ作る
            if (Directory.Exists(Path.GetDirectoryName(strChangeName)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(strChangeName));
            }
            //同名ファイルチェック
            string[] strFiles = Directory.GetFiles(strChangePath);
            if (s_bCopyAllFlag != 1)
            {
                foreach (string strSameFile in strFiles)
                {
                    if (s_bCopyAllFlag == 0 && strSameFile == strChangeName)
                    {
                        MessageForm form = new MessageForm(strSameFile);
                        DialogResult result = form.ShowDialog();
                        if (result == DialogResult.No)
                        {
                            return;
                        }
                        else if (result == DialogResult.Ignore)
                        {
                            s_bCopyAllFlag = 2;
                            return;
                        }
                        else if (result == DialogResult.OK)
                        {
                            s_bCopyAllFlag = 1;
                        }
                    }
                }
            }
            //リネーム後のファイルアクセス
            using (StreamWriter writer = new StreamWriter(new FileStream(strChangeName, FileMode.OpenOrCreate), RenameString.GetEncoding(strFile)))
            {
                //テキストはコピーしない
                if (TextCheckBox.Checked == false)
                {
                    straString = strbString;
                }
                writer.Write(straString);
            }
            //削除
            if (DeleteCheckBox.Checked == true)
            {
                Directory.Delete(strFile);
            }
        }
        //-------------------------------------------------------------------
        // コピーフォルダ
        //-------------------------------------------------------------------
        private void CopyPath(string strPath)
        {
            string[] strFiles = Directory.GetFiles(strPath);
            foreach (string strFile in strFiles)
            {
                CopyFile(strFile);
                if (s_bCopyAllFlag == 2) return;
            }
            //フォルダを追加
            string[] strDirectories = Directory.GetDirectories(strPath);
            foreach (string strDirectory in strDirectories)
            {
                if (SubFolderCheckBox.Checked == true)
                {
                    CopyPath(strDirectory);
                }
            }
        }
        //-------------------------------------------------------------------
        // コピーボタンクリック
        //-------------------------------------------------------------------
        private void CopyToolStripButton_Click(int type)
        {
            // 元のカーソルを保持
            Cursor preCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            s_bCopyAllFlag = 0;
            s_iCopyFileCounter = 0;
            CopyFileToolStripProgressBar.Minimum = 0;
            CopyFileToolStripProgressBar.Maximum = s_iCopyFileMax;
            if (type == 0)
            {
                CopyPath(BeforePathTextBox.Text);
            }
            else if (type == 1)
            {
                foreach (ListViewItem item in FolderLeftListView.SelectedItems)
                {
                    CopyFile(BeforePathTextBox.Text + "\\" + item.Text);
                }
            }
            else
            {
                Debug.Assert(true);
            }
            CopyFileToolStripProgressBar.Value = 0;
            FileNameToolStripStatusLabel.Text = "";
            statusStrip1.Update();
            //            MessageBox.Show("全コピー完了");
            Cursor.Current = preCursor;
        }
        //-------------------------------------------------------------------
        // コピーフォルダ
        //-------------------------------------------------------------------
        private void CountCopyPath(string strPath)
        {
            string[] strFiles = Directory.GetFiles(strPath);
            foreach (string strFile in strFiles)
            {
                s_iCopyFileCounter++;
            }
            //フォルダを追加
            string[] strDirectories = Directory.GetDirectories(strPath);
            foreach (string strDirectory in strDirectories)
            {
                if (SubFolderCheckBox.Checked == true)
                {
                    CountCopyPath(strDirectory);
                }
            }
        }
        //-------------------------------------------------------------------
        // ドラッグされた瞬間
        //-------------------------------------------------------------------
        private void listView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }
        //-------------------------------------------------------------------
        // ドラッグドロップ
        //-------------------------------------------------------------------
        private void listView_DragDrop(TextBox textBox, string[] dropPaths)
        {
            foreach (string path in dropPaths)
            {
                textBox.Text = (File.Exists(path)) ? Path.GetDirectoryName(path) : path;
            }
        }
        //-------------------------------------------------------------------
        // 前ドラッグアンドドロップ
        //-------------------------------------------------------------------
        private void listView1_DragDrop(object sender, DragEventArgs e)
        {
            listView_DragDrop(BeforePathTextBox, (string[])e.Data.GetData(DataFormats.FileDrop));
        }
        //-------------------------------------------------------------------
        // 後ドラッグアンドドロップ
        //-------------------------------------------------------------------
        private void listView2_DragDrop(object sender, DragEventArgs e)
        {
            listView_DragDrop(AfterPathTextBox, (string[])e.Data.GetData(DataFormats.FileDrop));
        }
        //-------------------------------------------------------------------
        // 前ボタンクリック
        //-------------------------------------------------------------------
        private void BeforePathButton_Click(object sender, EventArgs e)
        {
            DialogResult dr = BefreFolderBrowserDialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                BeforePathTextBox.Text = BefreFolderBrowserDialog.SelectedPath;
            }
        }
        //-------------------------------------------------------------------
        // 後ボタンクリック
        //-------------------------------------------------------------------
        private void AfterPathButton_Click(object sender, EventArgs e)
        {
            DialogResult dr = AfterfolderBrowserDialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                AfterPathTextBox.Text = AfterfolderBrowserDialog.SelectedPath;
            }
        }
        //-------------------------------------------------------------------
        // 前パステキストボックス変更
        //-------------------------------------------------------------------
        private void BeforePathTextBox_TextChanged(object sender, EventArgs e)
        {
            if (Directory.Exists(BeforePathTextBox.Text))
            {
                s_bLeftPathFlag = true;
                BeforePathTextBox.Text = RenameString.PathLastDel(BeforePathTextBox.Text);
                PathTextListViewAdd(s_bLeftPathFlag, s_bRightPathFlag);
                NameTextBox_TextChanged(sender, e);
            }
            else
            {
                s_bLeftPathFlag = false;
            }
        }
        //-------------------------------------------------------------------
        // 後パステキストボックス変更
        //-------------------------------------------------------------------
        private void AfterPathTextBox_TextChanged(object sender, EventArgs e)
        {
            if (Directory.Exists(AfterPathTextBox.Text))
            {
                s_bRightPathFlag = true;
                AfterPathTextBox.Text = RenameString.PathLastDel(AfterPathTextBox.Text);
                PathTextListViewAdd(s_bLeftPathFlag, s_bRightPathFlag);
                NameTextBox_TextChanged(sender, e);
            }
            else
            {
                s_bRightPathFlag = false;
            }
        }
        //-------------------------------------------------------------------
        // 名前テキストボックス変更
        //-------------------------------------------------------------------
        private void NameTextBox_TextChanged(object sender, EventArgs e)
        {
//            PathItemUpdate(FolderLeftListView, BeforePathTextBox.Text);
//            PathItemUpdate(FolderRightListView, AfterPathTextBox.Text);
            PathItemUpdate();
            ComboUpdate();
            SelectSourceAdd();
        }
        //-------------------------------------------------------------------
        // ダブルクリック
        //-------------------------------------------------------------------
        private bool listViewDoubleClick(ListView lv, TextBox tb)
        {
            if (lv.SelectedItems.Count > 1)
            {
                MessageBox.Show("ダブルクリックする時は選択を１つにしてください");
            }
            else if (lv.SelectedItems.Count == 1)
            {
                if (lv.SelectedItems[0].ImageIndex == (int)ItemType.ItemTop)
                {
                    FileInfo cFileInfo = new FileInfo(tb.Text);
                    if (cFileInfo.DirectoryName != null)
                    {
                        tb.Text = cFileInfo.DirectoryName;
                        return true;
                    }
                }
                else if (lv.SelectedItems[0].ImageIndex == (int)ItemType.ItemFolder)
                {
                    tb.Text += '\\' + lv.SelectedItems[0].Text;
                    return true;
                }
                else if (lv.SelectedItems[0].ImageIndex == (int)ItemType.ItemFile)
                {
                    tabControl1.SelectedTab = tabControl1.TabPages[1];
                }
            }
            return false;
        }
        //-------------------------------------------------------------------
        // 前ダブルクリック
        //-------------------------------------------------------------------
        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (FolderLeftListView.SelectedItems == null) return;
            if (listViewDoubleClick(FolderLeftListView, BeforePathTextBox))
            {
                BeforePathTextBox_TextChanged(sender, e);
            }
        }
        //-------------------------------------------------------------------
        // 後ダブルクリック
        //-------------------------------------------------------------------
        private void listView2_DoubleClick(object sender, EventArgs e)
        {
            if (FolderRightListView.SelectedItems == null) return;
            if (listViewDoubleClick(FolderRightListView, AfterPathTextBox))
            {
                AfterPathTextBox_TextChanged(sender, e);
            }
        }
        //-------------------------------------------------------------------
        // リネーム設定
        //-------------------------------------------------------------------
        private void BTextBox_TextChanged(object sender, EventArgs e)
        {
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo textInfo = cultureInfo.TextInfo;
            RenameString rename = new RenameString(BTextBox.Text);

            B1TextBox.Text = rename.TypeRename(RenameString.RenameType.Normal);
            B2TextBox.Text = rename.TypeRename(RenameString.RenameType.ToLower);
            B3TextBox.Text = rename.TypeRename(RenameString.RenameType.ToUpper);
            B4TextBox.Text = rename.TypeRename(RenameString.RenameType.FirstToUpper);
            B5TextBox.Text = rename.TypeRename(RenameString.RenameType.FirstToLower);
            B6TextBox.Text = rename.TypeRename(RenameString.RenameType.ToTitleCase);
            rename = rename.PlusRename(PreUpTextBox.Text);
            B7TextBox.Text = rename.TypeRename(RenameString.RenameType.Normal);
            B8TextBox.Text = rename.TypeRename(RenameString.RenameType.ToLower);
            B9TextBox.Text = rename.TypeRename(RenameString.RenameType.ToUpper);
            B10TextBox.Text = rename.TypeRename(RenameString.RenameType.FirstToUpper);
            B11TextBox.Text = rename.TypeRename(RenameString.RenameType.FirstToLower);
            B12TextBox.Text = rename.TypeRename(RenameString.RenameType.ToTitleCase);
        }
        //-------------------------------------------------------------------
        // 全部コピー
        //-------------------------------------------------------------------
        private void CheckCopyToolStripButton_Click(object sender, EventArgs e)
        {
            CopyToolStripButton_Click(0);
            NameTextBox_TextChanged(sender, e);
        }
        //-------------------------------------------------------------------
        // 選択コピー
        //-------------------------------------------------------------------
        private void SelectCopyToolStripButton_Click(object sender, EventArgs e)
        {
            CopyToolStripButton_Click(1);
            NameTextBox_TextChanged(sender, e);
        }
        //-------------------------------------------------------------------
        // 全ファイル
        //-------------------------------------------------------------------
        private void AllFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllFileRadioButton.Checked = true;
        }
        //-------------------------------------------------------------------
        // 選択のみ
        //-------------------------------------------------------------------
        private void RenameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RenameRadioButton.Checked = true;
        }
        //-------------------------------------------------------------------
        // ラジオボタン変更
        //-------------------------------------------------------------------
        private void RadioButton_CheckedChanged(object sender, EventArgs e)
        {
            BeforePathTextBox_TextChanged(sender, e);
            NameTextBox_TextChanged(sender, e);
        }
        //-------------------------------------------------------------------
        // センタークリック
        //-------------------------------------------------------------------
        private void CenterToolStripButton_Click(object sender, EventArgs e)
        {
            RenameSplitContainer.SplitterDistance = RenameSplitContainer.Width / 2;
        }
        //-------------------------------------------------------------------
        // 左クリック
        //-------------------------------------------------------------------
        private void LeftToolStripButton_Click(object sender, EventArgs e)
        {
            RenameSplitContainer.SplitterDistance = RenameSplitContainer.Width;
        }
        //-------------------------------------------------------------------
        // 右クリック
        //-------------------------------------------------------------------
        private void RightToolStripButton_Click(object sender, EventArgs e)
        {
            RenameSplitContainer.SplitterDistance = 0;
        }
        //-------------------------------------------------------------------
        // 選択項目の変更
        //-------------------------------------------------------------------
        private void listView3_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in RenameLeftlistView.SelectedItems)
            {
                SourceLeftComboBox.Text = item.Text;
                RenameLeftRichTextBox.SelectionStart = RenameLeftRichTextBox.Text.IndexOf(item.SubItems[2].Text);
                RenameLeftRichTextBox.SelectionLength = item.SubItems[2].Text.Length;
                RenameLeftRichTextBox.ScrollToCaret();
            }
        }
        //-------------------------------------------------------------------
        // 左選択項目の変更
        //-------------------------------------------------------------------
        private void FolderLeftListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in FolderLeftListView.SelectedItems)
            {
                SourceLeftComboBox.Text = item.Text;
                break;
            }
        }
        //-------------------------------------------------------------------
        // 右選択項目の変更
        //-------------------------------------------------------------------
        private void FolderRightListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in FolderRightListView.SelectedItems)
            {
                SourceRightComboBox.Text = item.Text;
                break;
            }
        }
        //-------------------------------------------------------------------
        // コンボボックス選択変更
        //-------------------------------------------------------------------
        private void SourceComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelectSourceAdd();
        }
        //-------------------------------------------------------------------
        // コンボボックステキスト変更
        //-------------------------------------------------------------------
        //お互いが参照しあって無限ループ回避
        static string SourceRightComboBoxText, SourceLeftComboBoxText;
        private void SourceLeftComboBox_TextChanged(object sender, EventArgs e)
        {
            if (SourceLeftComboBoxText != SourceLeftComboBox.Text)
            {
                SourceRightComboBox.Text = RenameString.SetRename(s_bRenameCheckBox, SourceLeftComboBox.Text, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                SourceLeftComboBoxText = SourceLeftComboBox.Text;
            }
        }
        private void SourceRightComboBox_TextChanged(object sender, EventArgs e)
        {
            if (SourceRightComboBoxText != SourceRightComboBox.Text)
            {
                SourceLeftComboBox.Text = RenameString.SetRename(s_bRenameCheckBox, SourceLeftComboBox.Text, BeforeNameTextBox.Text, AfterNameTextBox.Text, PreUpTextBox.Text);
                SourceRightComboBoxText = SourceRightComboBox.Text;
            }
        }
        //-------------------------------------------------------------------
        // スクロールバー同期
        //-------------------------------------------------------------------
        [DllImport("user32")]
        public static extern int GetScrollPos(IntPtr hWnd, int nBar);
        [DllImport("user32", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, IntPtr lParam);
        const int SB_THUMBPOSITION = 4;
        const int SB_VERT = 1;
        const int WM_VSCROLL = 0x0115;
        private void SourceLeftRichTextBox_VScroll(object sender, EventArgs e)
        {
            int pos = GetScrollPos(((Control)sender).Handle, SB_VERT);
            SendMessage(SourceRightRichTextBox.Handle, WM_VSCROLL, (pos << 16) | SB_THUMBPOSITION, IntPtr.Zero);
        }
        private void SourceRightRichTextBox_VScroll(object sender, EventArgs e)
        {
            int pos = GetScrollPos(((Control)sender).Handle, SB_VERT);
            //            SendMessage(SourceLeftRichTextBox.Handle, WM_VSCROLL, (pos << 16) | SB_THUMBPOSITION, IntPtr.Zero);
        }
        //-------------------------------------------------------------------
        // リネーム用チェックボックス変更
        //-------------------------------------------------------------------
        private void RenameCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            s_bRenameCheckBox[(int)RenameString.RenameType.Normal] = NormalCheckBox.Checked;
            s_bRenameCheckBox[(int)RenameString.RenameType.ToUpper] = ToupperCheckBox.Checked;
            s_bRenameCheckBox[(int)RenameString.RenameType.ToLower] = TolowerCheckBox.Checked;
            s_bRenameCheckBox[(int)RenameString.RenameType.FirstToUpper] = FirsttoupperCheckBox.Checked;
            s_bRenameCheckBox[(int)RenameString.RenameType.FirstToLower] = FirsttolowerCheckBox.Checked;
            s_bRenameCheckBox[(int)RenameString.RenameType.ToTitleCase] = TotitlecaseCheckBox.Checked;
            s_bRenameCheckBox[(int)RenameString.RenameType.PreUP] = PreupCheckBox.Checked;
        }
        //-------------------------------------------------------------------
        // ソースセーブ
        //-------------------------------------------------------------------
        private void SourceSaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in FolderLeftListView.SelectedItems)
            {
                string bFileName = BeforePathTextBox.Text + "\\" + item.Text;
                if (Directory.Exists(Path.GetDirectoryName(bFileName)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(bFileName));
                }
                using (StreamWriter writer = new StreamWriter(new FileStream(bFileName, FileMode.OpenOrCreate), RenameString.GetEncoding(bFileName)))
                {
                    writer.Write(SourceLeftRichTextBox.Text);
                }
            }
            PathTextListViewAdd(s_bLeftPathFlag, s_bRightPathFlag);
            PathItemUpdate();
            SelectSourceAdd();
        }
        //-------------------------------------------------------------------
        // 関数コメントオン
        //-------------------------------------------------------------------
        private void SourceFuncOnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strPlusFuncText = "";
            string[] strLines = SourceLeftRichTextBox.Lines;
            int iScopeCount = 0;
            foreach (string line in strLines)
            {
                if (line.IndexOf("}") != -1)
                {
                    iScopeCount--;
                    if (iScopeCount == 0)
                    {
                        strPlusFuncText += "#endif " + SourceFuncStripTextBox.Text + System.Environment.NewLine;
                    }
                }

                strPlusFuncText += line + System.Environment.NewLine;

                if (line.IndexOf("{") != -1)
                {
                    if (iScopeCount == 0)
                    {
                        strPlusFuncText += "#ifdef " + SourceFuncStripTextBox.Text + System.Environment.NewLine;
                    }
                    iScopeCount++;
                }
            }
            SourceLeftRichTextBox.Text = strPlusFuncText;
            SelectSourceAdd();
        }
        //-------------------------------------------------------------------
        // 関数コメントオフ
        //-------------------------------------------------------------------
        private void SourceFuncOffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strPlusFuncText = "";
            string[] strLines = SourceLeftRichTextBox.Lines;
            int iScopeCount = 0;
            for (int i = 0; i < strLines.Length; i++)
            {
                string line = strLines[i];
                string nextline = "";
                if (i != strLines.Length - 1)
                {
                    nextline = strLines[i + 1];
                }
                if (nextline.IndexOf("}") != -1)
                {
                    iScopeCount--;
                    if (iScopeCount == 0)
                    {
                        if (line.IndexOf(SourceFuncStripTextBox.Text) != -1)
                        {
                            continue;
                        }
                    }
                }
                strPlusFuncText += line + System.Environment.NewLine;
                if (line.IndexOf("{") != -1)
                {
                    if (iScopeCount == 0)
                    {
                        if (nextline.IndexOf(SourceFuncStripTextBox.Text) != -1)
                        {
                            i++;
                        }
                    }
                    iScopeCount++;
                }
            }
            SourceLeftRichTextBox.Text = strPlusFuncText;
            SelectSourceAdd();
        }
        //-------------------------------------------------------------------
        // テキスト変更
        //-------------------------------------------------------------------
        private void SourceLeftRichTextBox_TextChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in FolderLeftListView.SelectedItems)
            {
                item.Tag = SourceLeftRichTextBox.Text;
            }
        }
        private void SourceRightRichTextBox_TextChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in FolderRightListView.SelectedItems)
            {
               item.Tag = SourceRightRichTextBox.Text;
            }

        } 
    }
}
